﻿using System;
using System.Net;
using FluentValidation;
using Grundy.Common;
using Grundy.Message;
using Grundy.Message.Licensing;

namespace Grundy.Licensing.Server.Command
{
    public class CheckoutCommand : ICommand
    {
        private readonly LicenseSessionStore _licenseSessionStore;
        private static CheckoutRequestValidator _validator = new CheckoutRequestValidator();

        public CheckoutCommand(LicenseSessionStore licenseSessionStore)
        {
            _licenseSessionStore = licenseSessionStore;
        }

        public bool CanProcess(Request request)
        {
            return request is CheckoutRequest;
        }

        public Response Process(Request request, EndPoint requestingEndPoint, Guid customerId, string customerName)
        {
            return Process((CheckoutRequest)request, requestingEndPoint, customerId, customerName);
        }

        private Response Process(CheckoutRequest request, EndPoint requestingEndPoint, Guid customerId, string customerName)
        {
            _validator.ValidateAndThrow(request);
            request.FeatureIdentificationKey.CustomerId = customerId;
            request.FeatureIdentificationKey.CustomerName = customerName;

            var lri = new LicenseRequestInformation {ClientIdentifiers = request.Identifiers, FeatureIdentificationKey = request.FeatureIdentificationKey, EndPoint = requestingEndPoint};
            var sessionId = _licenseSessionStore.Checkout(lri);

            return new CheckoutSucceededResponse {SessionId = sessionId};
        }
    }
}